import 'package:baselib/utils/image_util.dart';
import 'package:baselib/utils/log_util.dart';
import 'package:flutter/material.dart';
import 'package:framelib/utils/color_util.dart';
import 'package:framelib/utils/drawable_util.dart';
import 'package:framelib/utils/px_util.dart';
import 'gift_type_model.dart';

/**
 * 商品分类
 */
class GiftTypeWidget extends StatefulWidget {
  List<GiftTypeModel> datas;
  int perHorNum;
  int perPageVerNum;
  Function onItemTap;
  Color backGroundColor;
  Color assetImageColor;
  double imgPadding;
  BoxFit imgFit;
  EdgeInsetsGeometry contMargin;
  bool isVertical;
  bool isShowNamePreImg;

  double barWidth;
  Color barSelectedColor;
  Color barUnSelectedColor;
  GiftTypeWidget({
    this.datas:const [],
    this.perHorNum:5,
    this.perPageVerNum:2,
    this.backGroundColor:Colors.white,
    this.assetImageColor,
    this.imgPadding,
    this.imgFit,
    this.contMargin,
    this.onItemTap,
    this.isVertical,
    this.isShowNamePreImg,
    this.barWidth,
    this.barSelectedColor,
    this.barUnSelectedColor,
  });
  @override
  _GiftTypeWidgetState createState() => _GiftTypeWidgetState();
}

class _GiftTypeWidgetState extends State<GiftTypeWidget> {

  List<GiftTypeModel>items=[];
  //每行多少个
  int perHorNum=5;
  //每页多少行
  int perPageVerNum=2;
  List<List<GiftTypeModel>>pageItems=[];
  //共多少页
  int pageNum=1;
  //余数
  int reNum=0;
  //递增标记
  int remarkNum=1;
  int mPageIndex=1;
  //被选中的下标
  int selectedIndex = -1;


  @override
  void initState() {
    // TODO: implement initState
    _CountData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Container(
          color: widget.backGroundColor,
          padding: EdgeInsets.only(
            top: 5,
//          left: 15,
//          right: 15,
          ),
          width: MediaQuery.of(context).size.width,
//          height: ((MediaQuery.of(context).size.width)/perHorNum)*(items?.length<=perHorNum?1:perPageVerNum)+pageItems.length*10,
          height: ((MediaQuery.of(context).size.width)/perHorNum)*(items?.length<=perHorNum?1:perPageVerNum)+10,
          child:
          PageView.builder(
              onPageChanged: (int pageIndex){
                mPageIndex=pageIndex+1;
                setState(() {});
              },
              itemCount: pageItems.length,
              itemBuilder: (BuildContext context,int index){
                return GridView.builder(
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: perHorNum,
                        mainAxisSpacing:10,
                        crossAxisSpacing: 0,
                        childAspectRatio: 1
                    ),
                    itemCount: pageItems[index].length,
                    itemBuilder: (BuildContext context,int innerIndex){
                      LogUtil.d('pageItems--->img=${pageItems[index][innerIndex]?.img},name=${pageItems[index][innerIndex]?.name}');
                      return GestureDetector(
                        child: Container(
                         // color: innerIndex==5?Colors.amberAccent:Colors.white,
                          child: Column(
                            mainAxisSize: MainAxisSize.max,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              (pageItems[index][innerIndex]?.img==null||('')==pageItems[index][innerIndex]?.img)?Container():
                              Container(
                                // padding: widget.imgPadding??EdgeInsets.all(PxUtil.instance.px_8),
                                width:((MediaQuery.of(context).size.width)/perHorNum-PxUtil.instance.px_15-PxUtil.instance.px_10-(widget.imgPadding??(PxUtil.instance.px_8*2))),
                                height:((MediaQuery.of(context).size.width)/perHorNum-PxUtil.instance.px_15-PxUtil.instance.px_10-(widget.imgPadding??(PxUtil.instance.px_8*2))),
                                decoration: BoxDecoration(
                                    border: Border.all(
                                        color: (selectedIndex== (index*perHorNum*perPageVerNum+innerIndex))?ColorUtil.instance.color_AC2EF2:ColorUtil.instance.color_transparent
                                    )
                                ),
                                child:((pageItems[index][innerIndex]?.img??'').startsWith('assets/'))?
                                ImagesUtil.loadAssetImage(
                                    pageItems[index][innerIndex]?.img??'',
                                  color: widget.assetImageColor??ColorUtil.instance.color_main,
                                  fit: widget.imgFit??BoxFit.cover,
                                ):ImagesUtil.loadNetworkImage(
                                    pageItems[index][innerIndex]?.img??'',
                                  fit: widget.imgFit??BoxFit.cover,
                                ),
                              ),
                              (pageItems[index][innerIndex]?.name==null||('')==pageItems[index][innerIndex]?.name)?Container():
                              Container(
                                margin:widget.contMargin?? EdgeInsets.only(
                                    top: PxUtil.instance.px_5,
                                ),
                                child: Center(
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      (!(widget.isShowNamePreImg??false))?SizedBox(width: 0,):
                                      ImagesUtil.loadAssetImage(
                                        DrawableUtil.instance.icon_gift_coin_img,
                                        width: PxUtil.instance.px_10,
                                        fit: BoxFit.fitWidth
                                      ),
                                      (!(widget.isShowNamePreImg??false))?SizedBox(width: 0,):
                                      SizedBox(width: PxUtil.instance.px_4,),
                                      Text(
                                        '${pageItems[index][innerIndex]?.name}',
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                            fontSize: 12,
                                            color: Color(0xffcacaca)
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              )
                            ],
                          ),
                        ),
                        onTap: (){
                          selectedIndex = (index*perHorNum*perPageVerNum+innerIndex);
                          if(widget.onItemTap!=null)widget.onItemTap(selectedIndex);
                          setState(() {});
                        },
                      );
                    }
                );
              }
          ),
        ),
        ((pageItems?.length??0)<=1)?Container(
          width: MediaQuery.of(context).size.width,
          height: 8,
        ):
        Container(
            width: MediaQuery.of(context).size.width,
            height: 24,
            color: widget.backGroundColor,
            alignment: Alignment.center,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children:pageItems.map((e) => Container(
                margin: EdgeInsets.only(
                  left: 1,
                  right: 1,
                ),
                child: Text(''),
                width: widget.barWidth??12,
                height: 4,
                decoration: BoxDecoration(
                    color: (pageItems.indexOf(e)==(mPageIndex-1)?widget.barSelectedColor??Color(0xfffd371d):widget.barUnSelectedColor??Color(0xffcccccc)),
                    borderRadius: BorderRadius.circular(10)
                ),
              )).toList(),
            )
        )
      ],
    );
  }

  void _CountData() {
    LogUtil.d('pageItems--->_CountData,datas=${widget.datas?.map((e) => e?.toString()).toList()}');
    items=widget.datas;
    perHorNum=widget.perHorNum;
    perPageVerNum=widget.perPageVerNum;
    pageNum=(items.length/(perHorNum*perPageVerNum)).toInt();
    reNum=(items.length%(perHorNum*perPageVerNum)).toInt();
    while(remarkNum<=pageNum&&pageNum>=1){
      List<GiftTypeModel>pageItemsCur=[];
      pageItemsCur.addAll(items.sublist((perHorNum*perPageVerNum*(remarkNum-1)),(perHorNum*perPageVerNum*(remarkNum))));
      pageItems.add(pageItemsCur);
      remarkNum++;
    }
    if(reNum!=0){
      List<GiftTypeModel>pageItemsCur=[];
      pageItemsCur.addAll(items.sublist((items.length-reNum),(items.length)));
      pageItems.add(pageItemsCur);
    }
    setState(() {});
  }
}
